package CSound {
	import UIFree.ObjectEvent;
	
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.MouseEvent;
	import flash.geom.Point;
	import flash.geom.Rectangle;
	import flash.media.Sound;
	import flash.media.SoundChannel;
	import flash.media.SoundTransform;
	import flash.net.URLRequest;
	
	public class ps_sound extends Object {
		private static const TITLE: String 		 = 'Добавление звука к открытке';
		private static const DESCRIPTION: String = 'Выберите из списка мелодию для добавления к открытке. Что бы посмотреть открытку вместе с музыкой, нажмите кнопку "Полный размер"';
		private static const DEFAULT_SOUNDS: Array = [
			{link: 'http://cdn1.appsmail.ru/hosting/456998/backstar.mp3', title:'--Вмайя, "Звезда"'},
			{link: 'http://cdn3.appsmail.ru/hosting/456998/self_done.mp3', title:'--Вмайя, "Моё продолжение"'},
			{link: 'http://cdn1.appsmail.ru/hosting/456998/ice.mp3', title:'--Вмайя, "Лед"'},
			{link: 'http://cdn8.appsmail.ru/hosting/456998/crusoe.mp3', title:'--Арт оф нойз, трек 1'},
			{link: 'http://cdn3.appsmail.ru/hosting/456998/static_state.mp3', title:'--Вмайя, "Стат. состояние"'},
			{link: 'http://cdn3.appsmail.ru/hosting/456998/Here%20the%20satan01.MP3', title:'--Вмайя, "Это сатана"'},
			{link: 'http://cdn1.appsmail.ru/hosting/456998/ajou.mp3', title:'--Вмайя, "ajou"'},
			{link: 'http://cdn5.appsmail.ru/hosting/456998/breath.mp3', title:'--Вмайя, "breath"'},
			{link: 'http://cdn2.appsmail.ru/hosting/456998/dino.MP3', title:'--Вмайя, "dino"'},
			{link: 'http://cdn3.appsmail.ru/hosting/456998/nde.mp3', title:'--Вмайя, "nde"'},
			{link: 'http://cdn1.appsmail.ru/hosting/456998/ajou.mp3', title:'--Вмайя, "ajou"'},
			{link: 'http://cdn5.appsmail.ru/hosting/456998/step%20to%20you%20v3.mp3', title:'--Вмайя, "Шаги к тебе"'},
			{link: 'http://cdn0.appsmail.ru/hosting/456998/up.mp3', title:'--Вмайя, "Вверх?"'}
		]
		
		public static const DEFVOLUME: Number = 0.3;
		
		private var _app: Object;
		private var _button: Object;
		private var _dialog: Object;
		private var _soundList: Object;
		private var _cList: Object;
		private var _sound: Sound;
		protected var _channel: SoundChannel;
		
		
		public function ps_sound(a_app: Object, dispatcher: EventDispatcher) {
			super();
			_app = a_app;
						
			dispatcher.addEventListener('CREATEUSERINTERFACE', createUI);
			dispatcher.addEventListener('PLUGINBTRELEASE', doShowDialog);
		}
		
		public function get app(): Object {
			return _app;
		}
		
		protected function createUI(e: ObjectEvent): void {
			//_button = _app.createExtButton(1, 'Добавить музыку к открытке', doShowDialog);
			createDialog();
		}

		protected function createDialog(): void {
			_dialog = new _app.classes['window'](_app.layers[4], 0, 0, 520, 300, 'window', true, 1);
			_dialog.position = new Point((_app.width - _dialog.width) / 2, (_app.height - _dialog.height) / 2);
			_dialog.title.text = TITLE;
			_dialog.addEvent('CLOSEWINDOW', soundStop);
			
			var inner: Rectangle = _dialog.getInner();
			var _pLayer: Object = new _app.classes['component'](_dialog, inner.x, inner.y + 60, inner.width, inner.height);
			var d_button: Object = new _app.classes['button'](_dialog, inner.x + inner.width - 80, inner.y + inner.height - 35, 80, 30, 'button');
			d_button.text = 'Ок';
			d_button.addEvent(MouseEvent.CLICK, doApply);
			
			
			var desc: Object = new _app.classes['label'](_dialog, inner.x, inner.y, inner.width, 50, 'description');
			desc.text = DESCRIPTION;
			
			inner = _pLayer.getInner();
			_cList = new _app.classes['searchlist'](_pLayer, inner.x, inner.y, inner.width, 182, 'list');
			
			_cList.addEvent('FILTER', function(e: ObjectEvent): void {
				var n: String = e.object.element.title.toLowerCase();
				var index: int = n.indexOf(e.object.word.toLowerCase());
				e.result = (index == 0)?true:(e.object.word=='');
			});
			
			_cList.addEvent('SELECT', doSelect);
			
		}
		
		protected function doSelect(e: Event): void {
			soundStop();
			if (_cList.selectIndex > 0) {
				_sound = new Sound(new URLRequest(_cList.list[_cList.selectIndex].link));
				_channel = _sound.play(0, 0, new SoundTransform(DEFVOLUME));
			}
		}
		
		protected function soundStop(e: Event = null): void {
			if (_channel) {
				_channel.stop();
				_channel = null;
			}
		}
		
		protected function doApply(e: Event = null): void {
			if (!app.cardbody.maskInfo.extend) app.cardbody.maskInfo.extend = new Object();
			
			if (_cList.selectIndex > 0) _app.cardbody.maskInfo.extend['SOUND'] = ['SOUND', //_name.text.replace(',', '0x002C'), 
															_cList.list[_cList.selectIndex].link, _cList.selectIndex];
			else delete(_app.cardbody.maskInfo.extend['SOUND']);
			_dialog.close(1);
		}
		
		protected function getAudios(handler_: Function): void {
	    	_app.externalserver.jsrHelper([
						{pn: "method", pv: "audios.get"},
						{pn: "uid", pv: _app.externalserver.viewer_id}
	    			], handler_, 'getAudios');
		}
		
		protected function attachList(): void {
			_cList.attachList(_soundList, function(area : Object, item: Object, index: int): Object {
				var c_item: Object = new _app.classes['label'](area, 0, index * 20, 490, 20, 'listItem');
				c_item.text = item.title;
				c_item._data = item;
				return c_item;
			});
		}
		
		protected function showDialog(): void {
			var params: Array = (_app.cardbody.maskInfo.extend && _app.cardbody.maskInfo.extend['SOUND'])?_app.cardbody.maskInfo.extend['SOUND']:['SOUND', '', 0];
			_cList.selectIndex = params[2];
			_dialog.show();
		}
		
		protected function doShowDialog(e: Event): void {
			if (!_soundList) {
				getAudios(function(data: Object): void {
					_soundList = data?data:[];
					_soundList = [{title:'без музыки'}].concat(_soundList);
					_soundList = _soundList.concat(DEFAULT_SOUNDS);
					attachList();
					showDialog();
				})
			} else showDialog();
		}
	}
}